import React from 'react'
import {Form, Row, Col, Modal, Input, Select, Tree, Button, Upload, Icon} from 'antd';
import API from "../../axios/api";
import {beforeUpload, checkUploadFiles} from '../../utils/utils'
import './form.less'
import config from '../../config';
const BaseUrl = config.apiURL

const { TextArea } = Input;

let id = 0

// @Form.create()
class ArticleForm extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [],
            treeData: [],
            editorContent: '',
            imgList: [],
            logImage:[],
            // fileList: [],
            clear: false,
            previewVisible: false,
            previewImage: '',
            fileList: [
                {
                    uid: '-1',
                    name: 'xxx.png',
                    status: 'done',
                    url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                },
            ],
            Id: "",
            shareImage: [],
            detailList: [{}]
        };
        this.ArticleLabelList = []
    }

    // 获取文章标签列表
    initArticleLabelList =  async () => {
        await API.fetchArticleLabelList().then((res) => {
            if(res.Code === 200) {
                this.ArticleLabelList =  res.Data
            }
        })
    }

    onExpand = expandedKeys => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    };

    onCheck = checkedKeys => {
        this.setState({ checkedKeys });
    };

    onSelect = (selectedKeys, info) => {
        this.setState({ selectedKeys });
    }

    componentWillMount() {
        const { form, data } = this.props;
        if(data){
            form.setFieldsValue({
                keys: data.keys,
                details: data.details
            });
        }
    }

    componentDidMount() {
        this.initArticleLabelList()
    }

    handleSubmit = e => {
        e && e.preventDefault()     

        this.props.form.validateFields((err, values) => {
            if (!err) {
                const { details } = values;
                values.image = values.ArticleLogo && values.ArticleLogo.length > 0 ? values.ArticleLogo[0].response.Data: ''

                if(details){
                    // ContentType = 内容1 ， 图片2， 视频3
                    details.map(item => {
                        if(item.file){
                            item.file.map(f => {
                                let _item = {
                                    Content: f.response.Data ,
                                    ContentType: f.type.includes('image') ? 2 : (f.type.includes('video')? 3: 1)
                                }
                                values.ArticleContentList.push(_item)
                            })
                        }
                        if(item.Content)
                        {
                            values.ArticleContentList.push({
                                ContentType: 1,
                                Content: item.Content
                            })
                        }
                    })
                }
                const { onOk } = this.props
                onOk && onOk(values)
                this.props.form.resetFields()
                this.setState({
                 logImage : [],
                  shareImage: []
                })
            }
        })
    }

    handlerClose = (fn) => {
        this.props.form.resetFields()
        this.setState({ checkedKeys : []})
        fn()
    }

    getRolePermByRoleId =  async (Id) => {
        const parms = {
            Id
        }
        await API.getRolePermissionByRoleId(parms).then((res) => {
            if(res.Code === 200) {
                let checkedKeys = res.Data
                this.setState({
                    checkedKeys
                });
            }
        })
    }


    onBlurEditor = (value) =>{
        this.setState({
            editorContent: value
        })
    }

    onImgUploadChange = (value) =>{
        this.setState({
            imgList : value
        })
    }

    componentWillReceiveProps(nextProps, nextContext) {
        if(nextProps.data){
            id = nextProps.data.keys ? nextProps.data.keys.length : 0
        }
    }

    shareNormFile = e => {
        if (Array.isArray(e)) {
            return e;
        }
        this.setState({
            shareImage: e.fileList
        })
        return e && e.fileList;
    }

    logNormFile= e => {
        if (Array.isArray(e)) {
            return e;
        }
        this.setState({
            logImage: e.fileList
        })
        return e && e.fileList;
    }

    normFile = e => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }

    addItem = (type) => {
        const { form } = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        const details = form.getFieldValue('details');
        // const nextKeys = keys.concat(id++);
        const nextKeys = keys.concat({id: id++, type: type});
        // can use data-binding to set
        // important! notify form to detect changes
        form.setFieldsValue({
            keys: nextKeys,
        });
    }

    remove = k => {
        const { form } = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        // We need at least one passenger
        if (keys.length === 1) {
            return;
        }

        // can use data-binding to set
        form.setFieldsValue({
            keys: keys.filter(key => key !== k),
        });
    };

    onRomoveImg = (data) =>{
        const { form } = this.props;
        const keys = form.getFieldValue('keys');
        const details = form.getFieldValue('details');
        form.setFieldsValue({
            details: data,
        });
    }

    render(){
        const { getFieldDecorator, getFieldValue } = this.props.form;

        const {
            modalKey,
            visible,
            title,
            fields,
            onCancel,
            onOk,
            okText,
            width,
            data,
            RankTypeList,
            rudderList,
            fen
        } = this.props

        let articleLogoFile = (data && data.ArticleLogo) || []
        let UploadImageUrl = BaseUrl + '/api/aboutapi/UploadImage'
        let UploadVideoUrl = BaseUrl + '/api/aboutapi/UploadVideo'
        getFieldDecorator('keys', {
            initialValue: data && data.keys ? data.keys: []
        });
      
     
        return (
            <Modal
                wrapClassName="form"
                key={modalKey}
                visible={visible}
                title={title}
                onCancel={onCancel}
                footer={null}
                width={width}
            >
                <Form className="ant-advanced-search-form" onSubmit={this.handleSubmit}>
                    <Row gutter={24}>
                    {
                        fen? ( <Col span={24} key="rudder" style={{ display: 'block' }}>
                        <Form.Item label="分舵名称">
                            {getFieldDecorator('rudder', {
                                rules: [{ required: true, message: '分舵名称必选' }],
                            })(
                                <Select>
                                    {
                                        rudderList && rudderList.map(item => {
                                            return (<option key={item.value} value={item.value}>{item.mean}</option>
                                            )
                                        })
                                    }
                                </Select>,
                            )}
                        </Form.Item>
                    </Col>) : ''


                    }
               
                        <Col span={24} key="RankTypeList" style={{ display: 'block' }}>
                            <Form.Item label="系统身份">
                                {getFieldDecorator('RankType', {
                                        rules: [{ required: true, message: '系统身份必选' }],
                                    })(
                                        <Select>
                                            {
                                                RankTypeList && RankTypeList.map(item => {
                                                    return (<option key={item.value} value={item.value}>{item.mean}</option>
                                                    )
                                                })
                                            }
                                        </Select>,
                                    )}
                                </Form.Item>
                            </Col>

                        <Col span={24} key="title" style={{ display: 'block' }}>
                            <Form.Item label={`头衔名称`}>
                                {getFieldDecorator(`Name`, {
                                    initialValue: data && data.Title,
                                    rules: [
                                        {
                                            required: true,
                                            message: 'Input something!',
                                        },
                                    ],
                                })(<Input placeholder="头衔名称" />)}
                            </Form.Item>
                        </Col>

                        <Col span={24} key="Description" style={{ display: 'block' }}>
                        <Form.Item label={`头衔描述`}>
                            {getFieldDecorator(`Description`, {
                                initialValue: data && data.Title,
                                rules: [
                                    {
                                        required: true,
                                        message: 'Input something!',
                                    },
                                ],
                            })(<Input placeholder="头衔描述" />)}
                          </Form.Item>
                      </Col>

                        <Col span={24} key="title" style={{ display: 'block' }}>
                           
                            <Form.Item label="头衔图片" >
                                {getFieldDecorator('ArticleLogo', {
                                    valuePropName: 'fileList',
                                    getValueFromEvent: this.logNormFile,
                                    initialValue: articleLogoFile
                                })(
                                    <Upload name="logo"
                                            action = {UploadImageUrl}
                                            listType="picture"
                                            beforeUpload={beforeUpload}
                                    >
                                        {this.state.logImage && this.state.logImage.length >0 ?  <br /> :
                                            <Button><Icon type="upload" />Click to upload</Button>
                                        }

                                    </Upload>,
                                )}
                            </Form.Item>
                        </Col>

                    </Row>
                    <Row>
                        <Col>
                            <div className="buttons">
                                {this.props.showCancel && <Button onClick={this.onCancel} >取消</Button>}
                                {!this.props.noBtn && <Button type="primary" htmlType="submit">{this.props.okText || '确定'}</Button>}
                            </div>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        )
    }
}
let ArticleModalForm = Form.create()(ArticleForm)
export default ArticleModalForm

